namespace PayPal.Platform.SDK
{
    using System;
    using System.IO;
    using System.Text;
    using System.Xml.Serialization;

    /// <summary>
    /// Summary description for XMLEncoder.
    /// </summary>
    public class XMLEncoder
    {
        public XMLEncoder()
        {
            // TODO: Add constructor logic here
        }

        public static string Encode(object obj)
        {
            StringWriter output = null;
            XmlSerializer serializer = null;

            try
            {
                using (output = new StringWriter(new StringBuilder()))
                {
                    serializer = new XmlSerializer(obj.GetType());
                    serializer.Serialize(output, obj);
                    return output.ToString();
                }
            }
            catch (FATALException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new FATALException("Error occurred in XMLEncoder->Encode method", ex);
            }
            finally
            {
                output = null;
                serializer = null;
            }
        }

        public static object Decode(string xmlEnvelope, Type toType)
        {
            XmlSerializer serializer = null;

            try
            {
                serializer = new XmlSerializer(toType);

                xmlEnvelope = xmlEnvelope.Replace("UTF", "utf").Trim();
                xmlEnvelope = xmlEnvelope.Replace("FaultMessage", "FaultDetailFaultMessage");
                xmlEnvelope = xmlEnvelope.Replace("ns2:", string.Empty);
                xmlEnvelope = xmlEnvelope.Replace("xmlns:ns2=\"http://svcs.paypal.com/types/ap\"", string.Empty);
                xmlEnvelope = xmlEnvelope.Replace("<parameter />", string.Empty);
                using (MemoryStream reader = new MemoryStream(Encoding.UTF8.GetBytes(xmlEnvelope)))
                {
                    return (object)serializer.Deserialize(reader);
                }
            }
            catch (FATALException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new FATALException("Error occurred in XMLEncoder->Decode method", ex);
            }
            finally
            {
                serializer = null;
            }
        }
    }
}

